PROGRESS_SIZE = 30

import time,sys
import tarfile
from glob import glob
import os
import re
from stat import *

from threading import Thread

DIR_NAME = "TarballDirectory"
BACK_DIR_NAME = ".."
VERSION_DIR_NAME = os.path.join(DIR_NAME, "Versions")

versionRegex = re.compile("iCurrentVersion = ([0-9]+)")


def getPatchTypes():
    return ["DLL", "Media", "Other", "Exit"]

class CompressThread( Thread ):
    def __init__(self, szFilename, szDirectory, pTarFile):
        self.szFilename = szFilename
        self.szDirectory = szDirectory
        self.pTarFile = pTarFile
        Thread.__init__(self)

    def run(self):
        for szFile in glob("*"):
            self.pTarFile.add(szFile)
        self.pTarFile.close()
        
def compress(szTarFile, szDirectory, pTarFile):
    print "Creating tar file...",
    pThread = CompressThread(szTarFile, szDirectory, pTarFile)
    pThread.start()
    while True:
        if not pThread.isAlive():
            break

    print " Done"

def getPatchVersionInfo():
    pPatchTypes = getPatchTypes()
    szFinalFilename = ""
    szFinalPatchType = ""
    for szFilename in glob(os.path.join(VERSION_DIR_NAME, "Current*Version.py")):
        for szPatchType in pPatchTypes:

            if szFilename.split("\\")[-1] == "Current%sVersion.py" % szPatchType:
                szFinalPatchType = szPatchType
                szFinalFilename = szFilename
                break
        if szFinalPatchType <> "":
            break

    iVersion = -1
    fTemp = open(szFinalFilename, "r")
    for line in fTemp.readlines():
        pMatches = versionRegex.match(line)
        if pMatches is not None:
            iVersion = int(pMatches.groups(0)[0])
            break

    fTemp.close()

    return szPatchType, iVersion

def getInputs():
    bOverrides = False
    iOverrideVersion = -1

    
    szInput = raw_input("Overrides? ([Y]es / [N]o): ")
    if szInput.upper() in ("Y", "YES"):
        bOverrides = True

    if bOverrides:
        iOverrideVersion = int(raw_input("\nEnter Version Override Start: "))
        
    return bOverrides, iOverrideVersion

def getCompressedMB(szTarballFilename):
    return float(os.stat(szTarballFilename)[ST_SIZE]) / (1024.0 * 1024.0)

def getPatchInfo(szPatchType, iVersion, iOverrides, dCompressedMB):
    szN = "%s%d" % (szPatchType, iVersion)
    szPatchInfo = """
    %s = {}
    %s["Date"] = '%s'
    %s["Version"] = %d
    %s["Filename"] = 'TODO'
    %s["Overrides"] = %d
    %s["Compressed Size"] = %.2f
    versions.append(%s)
    """

    szPatchInfo = szPatchInfo % (szN,
                                 szN, time.strftime("%b %d %Y", time.localtime()),
                                 szN, iVersion,
                                 szN,
                                 szN, iOverrides,
                                 szN, dCompressedMB,
                                 szN)

    return szPatchInfo


if __name__ == '__main__':
    if not os.path.exists(DIR_NAME):
        print "Could not find tarball directory. Make sure to run CreateTarballDir.py"
        exit

    szPatchType, iVersion = getPatchVersionInfo()
    bOverrides, iOverrideVersion = getInputs()

    szTarballFilename = "%sPatch%d.tar.gz" % (szPatchType, iVersion)
    pFile = tarfile.open(szTarballFilename, "w:gz")
    os.chdir(DIR_NAME)

    compress(szTarballFilename, DIR_NAME, pFile)

    pFile.close()

    os.chdir(BACK_DIR_NAME)

    pPatchFile = open("PatchFile.txt", "w")
    pPatchFile.write(getPatchInfo(szPatchType, iVersion, iOverrideVersion, getCompressedMB(szTarballFilename)))
    pPatchFile.close()

    raw_input("Press enter to end script")

